﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using Microsoft.SharePoint.WebPartPages;
using log4net;
using System.Reflection;

namespace AsyncWebPart
{
    [ToolboxItemAttribute(false)]
    public class AsyncWebPart : BaseWebPart, IWebEditable
    {
        #region Private Members
        private int _cacheMinutes = 0;
        private string _requestedStartRow = string.Empty;
        #endregion

        #region Public Properties
        [Personalizable(PersonalizationScope.Shared), WebBrowsable(false), DefaultValue("5000")]
        public string RowLimit
        {
            get;
            set;
        }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(false), DefaultValue(false)]
        public bool UsePaging
        {
            get;
            set;
        }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(false), DefaultValue(false)]
        public int CacheResultMinutes
        {
            get { return _cacheMinutes; }
            set { _cacheMinutes = value; }
        }
        #endregion

        #region Control Events

        protected override void OnLoad(EventArgs e)
        {
            try
            {
                EnsureChildControls();

                //Register script to automatically load the web part into the content container
                //Pass all the property values through asynchronous call
                this.Page.ClientScript.RegisterStartupScript(typeof(Page),
                    "startupScript" + this.ClientID,
                        string.Format("AsyncWebPartGetData('{0}','{1}','{2}','{3}','{4}', '{5}');",
                            (RowLimit != null) ? RowLimit.Replace("'", Constants.SingleQuoteReplacer) : "",
                            (UsePaging != null) ? UsePaging : false,
                            (CacheResultMinutes != null) ? CacheResultMinutes : 0,
                            (Page.Request.QueryString["startRow"] != null) ? Page.Request.QueryString["startRow"].ToString() : "",
                            String.Format("{0}_{1}_{2}", Constants.CacheKey_AsyncWebPart, CurrentUserId, this.ClientID),
                            _contentContainer.ClientID),
                    true);

                base.OnLoad(e);
            }
            catch (Exception ex)
            {
                Logger.Error("Error in AsyncWebPart.OnLoad", ex);
            }
        }

        protected override void CreateChildControls()
        {
            try
            {
                if (this.WebPartManager.DisplayMode.Name == "Browse")
                { this.AllowClose = false; }
                else
                { this.AllowClose = true; }

                _contentContainer = new Panel();

                //Prepare container to hold the content and add web service reference and js handler
                PrepareContentContainer();
                AddScriptManagerReferenceProxy(
                    Constants.WebServicePath_AsyncWebPart,
                    Constants.JSPath_AsyncWebPart);
            }
            catch (Exception ex)
            {
                Logger.Error("Error in CreateChildControls", ex);
            }
        }

        public override void RenderControl(HtmlTextWriter writer)
        {
            _contentContainer.RenderControl(writer);

            base.RenderControl(writer);
        }

        #endregion

        #region IWebEditable Members
        EditorPartCollection IWebEditable.CreateEditorParts()
        {
            //Return the editor part used with this web part.  This builds a
            //custom editor with dropdowns and an asset url selector.

            List<EditorPart> editors = new List<EditorPart>();
            editors.Add(new AsyncWebPartEditorPart());
            return new EditorPartCollection(editors);
        }
        #endregion

        #region Webpart Connections - Consumer
        /// <summary>
        /// Allows this web part to received filter values from other web parts.
        /// </summary>
        /// <param name="filterValues"></param>
        [ConnectionConsumer("Filter", "FilterInterface", AllowsMultipleConnections = false)]
        public void SetFilter(IFilterValues filterValues)
        {
            /* Connection logic here */
        }

        /// <summary>
        /// Get the filter value if available from the web part connection.
        /// </summary>
        /// <returns></returns>
        private string GetFilterValue()
        {
            /* Connection logic here */
            return string.Empty;
        }
        #endregion
    }
}
